package org.theSeed.filter;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
import org.theSeed.pojo.dto.UserInfoUserDetails;
import org.theSeed.rbacBaseCommon.pojo.constant.RbacConstant;
import org.theSeed.rbacSecurityJwt.utils.LoginUtil;
import org.theSeed.utils.LoginHelper;
import org.theSeed.web.utils.ServletUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * 认证过滤器
 */
public class AuthFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String authToken = ServletUtil.getHeaderValue(RbacConstant.AUTH_HEAER);
        if (ObjectUtil.isNotEmpty(authToken)){
            UserInfoUserDetails loginInfo = LoginUtil.getLoginInfo(LoginUtil.getToken(authToken));
            if (ObjectUtil.isNotNull(loginInfo)){
                LoginHelper.setLoginInfo(loginInfo);
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginInfo.getUsername(), null,loginInfo.getAuthorities());
                usernamePasswordAuthenticationToken.setDetails(loginInfo);
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
